<template>
	<view class="container bg-white text-lg">
		<!-- <button open-type="chooseAvatar" bindchooseavatar="getAvatar">
		    <image src="{{ avatarUrl }}" mode="" />
		  </button> -->
		<button class="lisItems flex align-center" open-type="chooseAvatar" @chooseavatar="getAvatar">
			<text>头&nbsp;&nbsp;像</text>
			<view class="flex-sub flex justify-end">
				<view class="imgbox">
					<image class="img" :src="avtoNewImg"></image>
				</view>
			</view>
		</button>
		<view class="lisItem flex align-center solid-bottom">
			<text>昵&nbsp;&nbsp;称</text>
			<view class="flex-sub text-end flex justify-end">
				<input class="uni-input textRight" type="nickname" v-model="form.nickNames" @focus="nickFo" @blur="nicBul" placeholder="请输入昵称" @change="getNickName"/>
			</view>
		</view>
		<view class="lisItem flex align-center solid-bottom">
			<text>性&nbsp;&nbsp;别</text>
			<view class="flex flex-sub justify-end">
				<view class="sex_item align-center justify-center flex solid" v-for="(item,index) in sexList" :key="index" :class="form.sex==item.value?'sexAct':''"
					@click="changeSex(item)">
					{{item.label}}
				</view>
			</view>
		</view>
		<view class="lisItem flex align-center solid-bottom">
			<text>电&nbsp;&nbsp;话</text>
			<view class="flex-sub text-end flex justify-end text-c9">
				{{form.phone||''}}
				<!-- <input class="uni-input textRight text-c6" type="tel" v-model="form.phone" disabled /> -->
			</view>
		</view>
		<view class="lisItem flex align-center solid-bottom">
			<text>生&nbsp;&nbsp;日</text>
			<view class="flex-sub text-end flex justify-end text-c6">
				<picker mode="date" :value="form.birPlaceholder" @change="bindDateChange" :disabled="birthdayDisable">
					<view class="uni-input" :class="{'text-c9':birthdayDisable}">{{form.birPlaceholder}}</view>
				</picker>
			</view>
			<text v-if="!birthdayDisable" class="cuIcon-right text-c6"></text>
		</view>
		<!-- <view class="lisItem flex align-center solid-bottom" @click="mnavTo('/pages/user/beOnDiet/beOnDiet')">
			<text>饮食禁忌</text>
			<view class="flex-sub text-end">
				<text class="cuIcon-right text-c6"></text>
			</view>
		</view> -->
		<!-- <view class="lisItem flex align-center solid-bottom">
			<text>BMI/新陈代谢</text>
			<view class="flex-sub text-end">
				<text class="cuIcon-right text-c6"></text>
			</view>
		</view> -->
		<view class="full_btn fixed" v-show="!isForce">
			<uni-transition :mode-class="['fade','slide-top']" :show="isLogin">
				<view class="mbtn gry" style="background:#53A87F;color: #fff;" @click="doSubmit">
					保存
				</view>
			</uni-transition>
			
			<view class="mbtn text-c3 margin-top-sm" :class="isLogin?'nbg':'lg'" @click="tapAct">
				{{isLogin?'退出登录':'登录'}}
			</view>
		</view>
		<btCropperVue watermark="" :watermarkType="1" mode="free" :url="avtoorImg" ref="cropper" @cancel="oncancel"
			@ok="onok" />
		<loading></loading>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from "vue";
	import global from '@/utils/global';
	import { onShow } from '@dcloudio/uni-app';
	import mapi from '@/utils/mapi';
	import { mnavTo, showLoading, hideLoading } from '@/utils/helper';
	import { queryMemberInfo,updateMember } from '@/api/vmeitime-http/index.js';
	import btCropperVue from "./jp-cropper-watermark/jp-cropper-watermark.vue";
	import {takeUserInfo} from '@/utils/public';
	import { env } from '@/api/env.js';
	import { useUserStore } from '@/stores/commonStore';
	const userStore = useUserStore();
	const avtoorImg = ref('');
	const cropper = ref();
	const paramsImg=ref('');
	const avtoNewImg = ref('../../../static/default_avos.png');
	const action = ref(env.FileUploadUrl + '/upload.do');
	const isForce = ref(false);
	const birthdayDisable=ref(false);
	const sexList = ref([
		{
			label: "男",
			value: 0
		}, {
			label: "女",
			value: 1
		}
	]);
	let form = ref<any>({
		nickNames: '',
		sex: 0,
		phone: "",
		birPlaceholder:'生日一旦填写无法修改'
	});
	const getNickName=(e:any)=>{
		form.value.nickNames=e.detail.value
	}
	const bindDateChange=(e:any)=>{
		form.value.birPlaceholder= e.detail.value
	}
	const changeSex = (item : any) => {
		form.value.sex = item.value
	}
	const tapAct = () => {
		isLogin.value ? loginOut() : toLogin()
	}
	const nickFo = () => {
		isForce.value = true
	}
	const nicBul = () => {
		isForce.value = false
	}
	const getAvatar = (e) => {
		let result = e.detail.avatarUrl.toLowerCase().includes('.gif')
		if(result){
			mapi.msg("暂不支持GIF格式")
			return
		}
		avtoorImg.value = e.detail.avatarUrl
	}
	const loginOut = () => {
		if (!isLogin.value) {
			return
		}
		uni.showModal({
			title: '提示',
			content: '确认退出登录',
			// showCancel: false,
			confirmText: '确认',
			confirmColor: '#56BF7A',
			success: res => {
				if (res.confirm) {
					uni.setStorageSync(global.USER_TIKET, '');
					uni.setStorageSync(global.IS_LOGIN, false);
					userStore.setSelectAdress();
					userStore.setChangeAdress(true);
					isLogin.value = false
					userStore.setUserInfo({})
					uni.switchTab({
						url:'/pages/index/user/user'
					})
				}
			}
		});
		// uni.setStorageSync(this.$global.USER_INFO, '');

	}
	const toLogin = () => {
		mnavTo('/pages/login/login')
	}
	const isLogin = ref(false)
	onShow(() => {
		console.log('onshow123');
		isLogin.value = uni.getStorageSync(global.IS_LOGIN) || false;
		getSettings()
	})
	const getSettings=async()=>{
		try{
			let res= await queryMemberInfo()
			if(!res.result||!res.object){
				return
			}
			const nres = res.object||{};
			form.value.nickNames=nres.vnick||'';
			avtoNewImg.value=(nres.vphoto==''||nres.vphoto==null)?'../../../static/default_avos.png':env.imgBaseUrl+nres.vphoto;
			form.value.phone=nres.vphone;
			form.value.birPlaceholder=(nres.vbirthday==""||nres.vbirthday==null)?'生日一旦填写无法修改':`${nres.vbirthday.slice(0, 4)}-${nres.vbirthday.slice(4, 6)}-${nres.vbirthday.slice(6)}`;
			birthdayDisable.value=nres.vbirthday?true:false;
			form.value.sex=nres.vsex=='177'?0:1;
			form.value.photos=nres.vphoto;
			console.log('birthdayDisable',birthdayDisable.value);
		}catch(e){
			//TODO handle the exception
		}
		
	}
	
	const oncancel = () => {
		// url设置为空，隐藏控件
		avtoorImg.value = ''
	}
	const onok = (ev : any) => {
		avtoorImg.value = ''
		// uploadImage(ev.path)
		avtoNewImg.value = ev.path
		paramsImg.value=ev.path
	}
	const uploadImage = (file : any) => {
		// var that = this;
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: action.value,//必填
				filePath: file,//必填，微信小程序只支持单文件上传
				name: 'uploadFile',//必填
				formData: {//发送给后端的附加参数
					'dirPath': 'goods',
					'resouceType': 1,
					'fileLimit': 1,
					'dataType': 198
				},
				// header: {
				// 	'Content-Type': 'multipart/form-data',
				// },
				success(res) {
					console.log('上传成功', res);
					if (res.statusCode == 200 && res.data) {
						const uploadFileRes = JSON.parse(res.data) || {};
						// console.log('res.data', uploadFileRes);
						resolve(uploadFileRes.folderPath + uploadFileRes.originalImgUrl);
					} else {
						reject('接口返回错误！');
					}
				},
				fail(e) {
					console.log('上传错误', e);
					reject('小程序上传报错！');
				}
			});
		});
	}
	const doSubmit=async()=>{
		showLoading()
		let chineseRegex = /[\u4e00-\u9fa5]/;
		let birthdayReg=chineseRegex.test(form.value.birPlaceholder)
		form.value.birthday=birthdayReg?'':form.value.birPlaceholder
		let resImg:any=''
		if(paramsImg.value!=''){
			resImg=await uploadImage(paramsImg.value)
		}else{
			resImg=form.value.photos
		}
    let params={
		 vphoto:resImg||'',
		 vnick:form.value.nickNames,
		 vbirthday:form.value.birthday!=''?form.value.birthday.replace(/-/g, ""):'',
		 vsex:form.value.sex==0?'177':'178'
	 }
	 let res = await updateMember(params);
	 await takeUserInfo();
	 if(!res.result){
		 mapi.msg(res.shortMessage?res.shortMessage:'网络繁忙，请稍后再试!')
		 hideLoading()
		 return
	 }
	 paramsImg.value=''
	 getSettings()
	 mapi.msg('保存成功!')
	 hideLoading()
	
	 // console.log(params,"params")
	}
</script>

<style lang="scss">
	.lisItem {
		height: 110rpx;
		padding: 0 30rpx 0 30rpx;
	}

	.lisItems {
		width: 100vw;
		height: 110rpx;
		background-color: #fff;
		color: #333;
		font-size: 32rpx;
		font-weight: 400;
		border-bottom: 1rpx solid #F8F8F8;
		border-top: 1rpx solid #fff;
		&::after{
			border-radius: 0;
			content: none;
		}
	}

	.imgbox,
	.img {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 6rpx;
	}

	.sex_item {
		width: 160rpx;
		height: 68rpx;
		// border: 1rpx solid #999;
		border-radius: 80rpx;
		color: #333;
    background: #fff;
		&:after{
			 border: 3rpx solid #999;
		}
		&:first-child {
			margin-right: 20rpx;
		}
	}

	.sexAct {
		border: 1rpx solid #53A87F;
		background: #53A87F;
		color: #fff;
	}
		
	.textRight{
		text-align: right;
	}
	.mbtn{
		&.nbg{
			color: #333!important;
		}
	}
</style>